package cn.fanxin.utils;

import cn.fanxin.tools.MyException;

import java.io.*;

/**
 * @Author：china-fanxin
 * @Website: https://fan-xin.cn
 * @Date 2023/3/3 10:12
 * @Description:
 */
public class FileUtils {

    /**
     * @Author: china-fanxin
     * @Website: https://fan-xin.cn
     * @Description:  文件输出通用工具
     * @Date 2023/3/3 10:16
     * @Param: [filePath, content]
     * @Return: void
     */
    public static void fileOutPut(String filePath,String content){
        File file = new File(filePath);
        //如果文件不存在，创建文件
        try{
            if (!file.exists())
                file.createNewFile();
            //创建FileOutputStream对象，写入内容
            FileOutputStream fos = new FileOutputStream(file);
            //向文件中写入内容
            fos.write(content.getBytes());
            fos.close();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * @Author: china-fanxin
     * @Website: https://fan-xin.cn
     * @Description: 文件内容读取通用工具
     * @Date 2023/3/3 10:16
     * @Param: [filePath]
     * @Return: void
     */
    public static void fileInput(String filePath) {
        //创建FileInputStream对象，读取文件内容
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            throw new MyException("Error:"+filePath+"不存在");
        }
        byte[] bys = new byte[100];
        try {

            while (fis.read(bys, 0, bys.length) != -1) {
                //将字节数组转换为字符串
                System.out.println(new String(bys));
            }
            fis.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
